gpt4 book ai didi

javascript - 如何将数组从 ["1","2","3","4"] 转换为 [1,2,3,4]?

转载 作者:行者123 更新时间:2023-12-02 23:55:29 25 4
gpt4 key购买 nike

我正在尝试使用以下代码行 block

var myarray = [1,2,3,4];
var new_array = [];
myarray.reduce(function(a,b,i) { return new_array[i] = a+b; },0);
// Result = [1, 3, 6, 10]
console.log("original array");
console.log(new_array);

这个 block 工作得很好,但是当我替换我自己的数组时,结果完全错误

var ar1 = ["1","2","3","4"];
var ar2 = [];
ar1.reduce(function(a,b,i) { return ar2[i] = a+b; },0);
// result = ["01", "012", "0123", "01234"]
console.log("original array");
console.log(ar2);

我得到这个结果[“01”,“012”,“0123”,“01234”]

谁能帮忙,谢谢

最佳答案

在使用+运算符之前,尝试parseIntNumber转换为StringString + String 是字符串连接,而 Number + Number 是代数加法

var ar1 = ["1","2","3","4"];
var ar2 = [];
ar1.reduce(function(a,b,i) { return ar2[i] = parseInt(a) + parseInt(b); },0);
// result = ["01", "012", "0123", "01234"]
console.log("original array");
console.log(ar2);

关于javascript - 如何将数组从 ["1","2","3","4"] 转换为 [1,2,3,4]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55409141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com