“concat”没有将 JavaScript 数组连接在一起?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12810366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:10:29  来源:igfitidea点击:

"concat" does not join JavaScript arrays together?

javascriptarrays

提问by I Hate Lazy

I'm running the following code on Webkit:

我在 Webkit 上运行以下代码:

var scriptElements = document.scripts;
var scriptUrls = [];
// URL matching
var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>???“”‘']))/i;
for (var i = 0; i < scriptElements.length; i++) {
    element = scriptElements[i];
    var urls = element.innerHTML.match(regexp);
    console.log('local', urls);
    scriptUrls.concat(urls);
    console.log('global', scriptUrls);
}

I see non-empty arrays printed after 'local' but the 'global' always stays as an empty array. What's going on?

我看到在“本地”之后打印了非空数组,但“全局”始终保持为空数组。这是怎么回事?

回答by I Hate Lazy

.concatcreates a new Array. You need to overwrite the old one.

.concat创建一个新数组。你需要覆盖旧的。

scriptUrls = scriptUrls.concat(urls);


Or if you want to keep the original scriptUrlsArray, you can .push()the values in.

或者,如果您想保留原始scriptUrls数组,则可以.push()将值放入。

scriptUrls.push.apply(scriptUrls, urls);

This uses .apply()to convert urlsinto individual arguments passed to .push(). This way the content of urlsis added to scriptUrlsas individual items.

这用于.apply()转换urls为传递给的单个参数.push()。通过这种方式, 的内容urls被添加scriptUrls为单独的项目。



Also, note that .concat()flattensthe Array. If you wanted an Array of Arrays, then you'd use scriptUrls.push(urls).

另外,请注意展.concat()数组。如果你想要一个数组数组,那么你会使用scriptUrls.push(urls).

回答by spender

concat does not alter this or any of the arrays provided as arguments but instead returns a "one level deep" copy that contains copies of the same elements combined from the original arrays.

concat 不会改变这个或任何作为参数提供的数组,而是返回一个“一级深”副本,其中包含从原始数组组合的相同元素的副本。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/concat

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/concat