gpt4 book ai didi

javascript - 为什么 splice 返回的是字符串而不是数组?

转载 作者:行者123 更新时间:2023-11-30 08:14:33 24 4
gpt4 key购买 nike

我正在尝试从二维数组 arr 拼接数组 two

var one = ["a","b"];  
var two = ["c","d"];
var thr = ["e","f"];
var arr = [one,two,thr];

这是我的两次失败尝试:

1)

var rem = arr.splice(1,1);  
alert(rem[0]);
// This alerts the entire array as one long string "c,d".
// The expected behavior is "c" (index 0 of the returned array _rem_).

2)

var rem = arr[1].splice(0);  
alert(arr);
// The array _rem_ is now correct, but _arr_ is left with an empty index: "a,b,,e,f".

我有一个不太理想的解决方法,但我希望通过一个函数来完成。

var test = arr[1].slice(0);  
arr.splice(1,1);

最佳答案

有趣的观察。来自 ECMA 规范(262,第 5 版):

When the splice method is called with two or more arguments start, deleteCount and (optionally) item1, item2, etc., the deleteCount elements of the array starting at array index start are replaced by the arguments item1, item2, etc. An Array object containing the deleted elements (if any) is returned.

Array.splice 因此返回已删除元素的数组。所以,如果你想引用删除的数组,这应该是语法:

var rem = arr.splice(1,1)[0];
alert(rem[0]); //=> 'c'

关于javascript - 为什么 splice 返回的是字符串而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5846356/

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