Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  100] [ 7]  / answers: 1 / hits: 15919  / 12 Years ago, wed, october 10, 2012, 12:00:00

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%])|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?


More From » arrays

 Answers
13

.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).


[#82649] Monday, October 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;