Home > database >  Why can't we create static array with custom keys in javascript in one single line like PHP
Why can't we create static array with custom keys in javascript in one single line like PHP

Time:11-19

Trying to declare an static array in Javascript:

let arr = ['a':'a1','b':'b2','c':'c3'] //gives error

Trying to declare an static array in PHP:

$arr = ['a'=>'a1','b'=>'b2','c'=>'c3'] //works

Objects can be made using {} why not array with [] having custom keys?

I am not compating Js and PHP but just a big WHY ? Why only Objects not Array ?

CodePudding user response:

Your problem is that you are not using {}, but []. [] are arrays - not objects. {} are objects - very json-like, but can contain everything - from numbers to functions

CodePudding user response:

Using the built-in Array type in JavaScript, I believe this is as close as you can get, using Object.assign to clone named properties from an object to an Array object. But it's very doubtful if this will actually do what you think it will do.

const a = Object.assign([1,2,3], {a:4, b:5, c:6});

You can do this because an array IS an object, just of a special type, with special Array.prototype functions for dealing with its numerically keyed members.

But if you were thinking you would be able to use things like .map or .forEach to loop through (non-numerically) named properties, it won't work. Those are special cases that only work with numerically keyed array items. Try doing this with the above array:

a.forEach(x=> console.log(x));
// output:
// => 1
// => 2
// => 3

the a/b/c properties don't show up.

A better solution, and more likely to do what you actually want, would be to make your own custom "class," something like this:

function NamedArray(init) {
  Object.assign(this, init);
}
NamedArray.prototype.forEach = function(callback) {
  const keys = Object.entries(this);
  keys.forEach(([key, value],array)=> callback(value, key, array));
}

const arr = new NamedArray({a:1,b:2,c:3});
arr.forEach((value,key)=> {
  console.log(key, value);
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can create all the class methods that you need, using this pattern.

Note: There is also ES6 syntax for creating these classes, which can make creating objects with lots of prototype methods and properties much easier.

  • Related