js操作对象和数组对象 取keyvalue

JavaScript015

js操作对象和数组对象 取keyvalue,第1张

var people = [

  { "name": "bob", "dinner": "pizza" },

  { "name": "john", "dinner": "sushi" },

  { "name": "larry", "dinner": "hummus" }

]

people.filter(function (person) { 

  if(person.dinner){

    console.log(person.dinner)

  }

  if(person.name){

    console.log(person.name)

  }

})

var people1 = { "name": "bob", "dinner": "pizza" }

Object.keys(people1)

console.log(Object.keys(people1))

var jsonObj = {"1" : 50,"2" : 40,"3" : 40,"4" : 30,"5" : 20,"6" : 20,"7" : 20,"8" : 20,"9" : 20, "10" : 20}

var keyAry = []

var valueAry = []

for(var key in jsonObj){

  keyAry.push(key)

  valueAry.push(jsonObj[key])

}

console.log(keyAry)

console.log(valueAry)

你这样存进去的是没有key的,正确的写法应该是

var a=new Array({key:'1',value:"a"},{key:'2',value:"b"},{key:'3',value:"c"},{key:'4',value:"d"})

下面写了个例题

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE>New Document </TITLE>

<META NAME="Generator" CONTENT="EditPlus">

<META NAME="Author" CONTENT="">

<META NAME="Keywords" CONTENT="">

<META NAME="Description" CONTENT="">

</HEAD>

<BODY>

<SCRIPT LANGUAGE="JavaScript">

<!--

function Map( ){

this.elements = new Array()

this.init = function( _e ){

this.elements = _e

}

this.put = function(key, value) { // 加入元素

this.elements.push({key: key, value:value})

}

this.getByValue = function( _value) { // 取出对应value

try{

for (i = 0i <this.elements.lengthi++) {

if (this.elements[i].value == _value) {

return this.elements[i].key

}

}

}catch(e) {

return null

}

}

this.getByKey = function( _key) { // 取出对应key

try{

for (i = 0i <this.elements.lengthi++) {

if (this.elements[i].key == _key) {

return this.elements[i].value

}

}

}catch(e) {

return null

}

}

}

//使用例题

var a=new Array({key:'1',value:"a"},{key:'2',value:"b"},{key:'3',value:"c"},{key:'4',value:"d"})

var value = "b"

var map = new Map()

map.init( a )

alert( map.getByValue( value ) )

//-->

</SCRIPT>

</BODY>

</HTML>