gpt4 book ai didi

javascript - 为什么数组串联在 Javascript 中不起作用?

转载 作者:行者123 更新时间:2023-11-28 18:43:20 26 4
gpt4 key购买 nike

当我在 JavaScript 中创建两个数组并尝试使用 concat 连接它们时关键字,结果数组总是空的(好吧,数组中应该插入的东西没有插入)。我无法想象这实际上是 JS 应该如何工作的,因为那么...... concat 的意义是什么?关键字如果什么都不做?

那么我一定做错了什么,但我完全遵循文档。

这是一个演示我的问题的 fiddle :https://jsfiddle.net/webwhizjim/7z4v33of/

// Example with objects- doesn't work...
var greetings = [{"affirmative":"yeah"}];
var exclamations = [{"omg":"Oh my golly-gee-wilickers!"},{"wowz":"wowzers!"}];

var obArray = [];

obArray.concat(greetings);
console.log("The jumble array is: " + obArray);

// Example with strings- still doesn't work...

var greetings2 = ["affirmative","yeah"];
var exclamations2 = ["omg"];

var obArray2 = ["huh?"];

[].concat.call(obArray2, greetings2);
console.log("The jumble array is: " + obArray2);

为了明确“它不起作用”,我的意思是控制台输出是这样的:

enter image description here

PS。在我的实际项目中,我使用的是 Angular 1.4;所以,如果有办法 concat数组,我对此持开放态度。

最佳答案

.concat() 创建一个新数组并返回它。它不会将元素添加到现有数组中。

来自MDN :

concat creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array).

concat does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays. Elements of the original arrays are copied into the new array as follows:

您可以使用 .splice().push() 将元素添加到现有数组中。

var greetings2 = ["affirmative","yeah"];
var obArray2 = ["huh?"];
obArray2.push.apply(obArray2, greetings2);

// display result in snippet
document.write(JSON.stringify(obArray2));

<小时/>

或者,只需使用 .concat() 新返回的数组:

    var greetings2 = ["affirmative","yeah"];
var obArray2 = ["huh?"];
var newArray = obArray2.concat(greetings2);

// display result in snippet
document.write(JSON.stringify(newArray));

关于javascript - 为什么数组串联在 Javascript 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35779096/

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