What\'s the most efficient way to create this simple array dynamically.
var arr = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];
<
misread the question, corrected. Try:
var myNumber = 100,
myarr = (function arr(i){return i ? arr(i-1).concat(i) : [i]}(myNumber));
Just for fun, if you extend Array
like this:
Array.prototype.mapx = function(callback){
return String(this).split(',').map(callback);
}
You could use:
var myNum = 100,
myarr = new Array(myNum).mapx(function(el,i){return i+1;});
With ES2015, this can be achieved concisely in a single expression using the Array.from
method like so:
Array.from({ length: 10 }, (_, idx) => `${++idx}`)
The first argument to from
is an array like object that provides a length property. The second argument is a map function that allows us to replace the default undefined
values with their adjusted index values as you requested. Checkout the specification here
var arr = [];
for(var i=1; i<=mynumber; i++) {
arr.push("" + i);
}
This seems to be faster in Chrome, according to JSPerf, but please note that it is all very browser dependant.
There's 4 things you can change about this snippet:
for
or while
.push
or direct access by index.toString
.In each and every browser total speed would be combination of how much better each option for each item in this list performs in that particular browser.
TL;DR: it is probably not good idea to try to micro-optimize this particular piece.
for (var j = 0; j <= data.legth -1; j++) {
lang += data.lang +", " ;
}
var langs = lang.split(',')
console.log("Languages =>", lang, typeof(lang), typeof(langs), langs)
console.log(lang[0]) // here access arrary by index value
you can see the type of string and object
I hope you have to get last element from array variable so my solution
var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var mynumber = arr [arr .length - 1];
//var mynumber = 10;
Update: micro-optimizations like this one are just not worth it, engines are so smart these days that I would advice in the 2020 to simply just go with
var arr = [];
.
Here is how I would do it:
var mynumber = 10;
var arr = new Array(mynumber);
for (var i = 0; i < mynumber; i++) {
arr[i] = (i + 1).toString();
}
My answer is pretty much the same of everyone, but note that I did something different:
So I created the array with new Array(mynumber);