Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

"concat" does not join JavaScript arrays together?

I'm running the following code on Webkit:

var scriptElements = document.scripts;
var scriptUrls = [];
// URL matching
var regexp = /((?:[a-z][w-]+:(?:/{1,3}|[a-z0-9%])|wwwd{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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

scriptUrls = scriptUrls.concat(urls);

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

scriptUrls.push.apply(scriptUrls, urls);

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.


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...