简体   繁体   中英

javascript push key value

In my mind I want to push a key-value on array.

Say for example in PHP this is done like this:

$err = array();
function check($k,$v) {
  $err[$k] = $v; 
}

How is this done exactly in JavaScript/jQuery?

Javascript key/value pair support in Object , not in Array

Insert Element:

var arr= [1,2,3],
    result = {};

for(var key in arr) {
   result[key] = arr[key]; // in this case key will be 0,1,2 i.e index of array element
}

Check that a key exists:

function checking(k, v) {
  if(result.k != null || result.k !=  undefined) {
    // do something
  }
}

According to your function:

var err = {}; // not array, should be object
function check(k,v) {
  err[k] = v; // or err.k = v;
}

More on insert:

var x = [];

x.some = 'some'; // OK; arrays are objects
x['some'] = 'some'; // exactly the same

Get value:

x.home; // give 'some'
x['home']; // give 'some'

Count length:

If you want to get length of an array you have to use .length .

For example:

x.length; // will return 1

And if you want to count the length of an Object:

var obj = {a: 'XYZ', b: 'PQR'};

Object.keys(obj).length; // will return 2

To Delete item:

if you want to remove an item from an Object:

delete obj[key];

to delete an item from an array:

delete arr[index]; // index is position of the element within array

also to remove array element you can do

arr.splice(0,2); // splice(index, howmany, [item1, item2, ...., itemx])
                 // in this example from start 2 items will delete

You use an object. And do it in much the same way.

var $err = {};
function check($k, $v) {
     $err[$k] = $v;
}

Granted, that's not an array though.

Do take note that you can actually do this in Javascript arrays, and the interpreter will let you.

var $err = []; // an array
function check($k, $v) {
    $err[$k] = $v;
}

But you're not really pushing to the array, but rather extending the array object . You can check this out with this:

var foo = [];
foo['hello'] = 'world';

console.log(foo);            // []
console.log(foo['hello']);   // 'world'
console.log(foo.hello);      // 'world'
console.log(foo.length);     // 0

... so best to watch out for this gotcha. :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM