“连接"不将 JavaScript 数组连接在一起? [英] "concat" does not join JavaScript arrays together?

查看:32
本文介绍了“连接"不将 JavaScript 数组连接在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Webkit 上运行以下代码:

I'm running the following code on 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?

推荐答案

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

.concat creates a new Array. You need to overwrite the old one.

scriptUrls = scriptUrls.concat(urls);

<小时>

或者如果你想保留原来的scriptUrls数组,你可以.push()里面的值.


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

scriptUrls.push.apply(scriptUrls, urls);

这使用 .apply()urls 转换为传递给 .push() 的单个参数.这样,urls 的内容就作为单独的项目添加到 scriptUrls 中.

This uses .apply() to convert urls into individual arguments passed to .push(). This way the content of urls is added to scriptUrls as individual items.

另外,请注意 .concat() 扁平化 Array.如果你想要一个数组数组,那么你可以使用 scriptUrls.push(urls).

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

这篇关于“连接"不将 JavaScript 数组连接在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆