Is there a way to assign a default values to arrays in javascript?
ex: an array with 24 slots that defaults to 0
Is there a way to assign a default values to arrays in javascript?
ex: an array with 24 slots that defaults to 0
Array.prototype.repeat= function(what, L){
while(L) this[--L]= what;
return this;
}
var A= [].repeat(0, 24);
alert(A)
repeat = function(what, count, isFactory) { ... }; [].repeat(function() { return new myObject(); }, 10, true);
–
Ventris repeat
as ES6 will implement a repeat
method, meaning you will overwrite default behaviour, which is discouraged. Good solution though. –
Beberg You can use the fill
function on an array:
Array(24).fill(0)
Note: fill
was only introduced in ECMAScript 2015 (alias "6"), so as of 2017 browser support is still very limited (for example no Internet Explorer).
var a = Array.apply(null, Array(24)).map(function() { return 0 });
// or:
var a = Array.apply(null, Array(5)).map(Boolean).map(Number);
Array.prototype.repeat= function(what, L){
while(L) this[--L]= what;
return this;
}
var A= [].repeat(0, 24);
alert(A)
repeat = function(what, count, isFactory) { ... }; [].repeat(function() { return new myObject(); }, 10, true);
–
Ventris repeat
as ES6 will implement a repeat
method, meaning you will overwrite default behaviour, which is discouraged. Good solution though. –
Beberg the best and easiest solution is :
Array(length of the array).fill(a default value you want to put in the array)
example
Array(5).fill(1)
and result will be
[1,1,1,1,1]
you can put any thing you like in it:
Array(5).fill({name : ""})
Now if you want to change some of the current value in the array you can use
[the created array ].fill(a new value , start position, end position(not included) )
like
[1,1,1,1,1].fill("a",1,3)
and output is
[1, "a", "a", 1, 1]
A little wordy, but it works.
var aray = [ 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0 ];
If you use a "very modern" browser (check the compatibility table), you can rely on fill
:
var array = new Array(LENGTH);
array.fill(DEFAULT_VALUE);
For several reasons, the use of new Array()
is not appreciated by a lot of developers; so you can do the same as follows:
var array = [];
for(var i=0; i<LENGTH; ++i) array.push(DEFAULT_VALUE);
The latter is much more compatible, and as you can see both solutions are represented by two lines of code.
If you are using ES6 and up you can use
new Array(24).fill(0);
this also works:
Array.from({ length: 24}, () => 0)
No.
You have to use a loop.
var a = new Array(24);
for (var i = a.length-1; i >= 0; -- i) a[i] = 0;
I personally use:
function replicate (n, x) {
var xs = [];
for (var i = 0; i < n; ++i) {
xs.push (x);
}
return xs;
}
Example:
var hellos = replicate (100, "hello");
And now, more cleverly :)
@see JavaScript Array reference
Example on JSFiddle
var len = 100;
var ch = '0';
alert ( new Array(len).join( ch ) );
Array(24).join().split('').map(function(){return 0})
–
Pediment Use Lodash
(https://lodash.com/docs), a robust library for array manipulation which is available for browser too.
var _ = require('lodash');
var A = _.fill(Array(24), 0);
Simplest one:
myArray = new Array(24).fill(0)
Another way to achieve the same -
Array.from(Array(24),()=>5)
Array.from
accepts a second param as its map function.
Syntax which i am using below is based on ECMA Script 6/es6
let arr=[];
arr.length=5; //Size of your array;
[...arr].map(Boolean).map(Number); //three dot operator is called spread Operator introduce in ECMA Script 6
------------Another way-------------
let variable_name=new Array(size).fill(initial_value)
for ex- let arr=new Array(5).fill(0) //fill method is also introduced in es6
Another way as per ECMA 5 or es5
var variable_name=Array.apply(null,Array(size)).map(Boolean).map(Number)
var arr=Array.apply(null,Array(5)).map(Boolean).map(Number);
All of them will give you same result : [0,0,0,0,0]
// 1-D array
// array with length 3 and defaults to null
Array(3).fill(null);
/*
This will look like
[null, null, null]
*/
// for, 2-D array
// array with length 3 and default value an array of length 3
Array(3)
.fill(null)
.map(() => Array(3).fill(null));
/*
This will look like
[[null, null, null],
[null, null, null],
[null, null, null]]
*/
(new Array(5).toString().replace(/,/g, "0,") + "0").split(",")
// ["0", "0", "0", "0", "0"]
var a = new Array(6).join(0).split('')
? –
Epictetus If you want BigO(1) instead of BigO(n) please check below solution:
Default value of an array is undefined
. So if you want to set default to 0, you have to loop all elements of array to set them to 0.
If you have to do that, it's ok. But I think it'll better if you check the value when want to get value of the element.
Define a function 'get': to get value of the array. myArray[index], if myArray[index] undefined, return '0', else return the value.
const get = (arr, index) => {
return arr[index] === undefined ? 0 : arr[index];
}
Use:
const myArray = ['a', 'b', 1, 4];
get(myArray, 2); // --> 'b'
get(myArray, 102344); // --> 0;
function get (i) { return 0; }
–
Chally © 2022 - 2024 — McMap. All rights reserved.