简体   繁体   中英

Iterating object objects correctly in JavaScript

var obj = {a: 1, b: 2, c:3}    

Object.keys(obj).forEach(function(x){
    console.log(obj[x])
})

This gives: 1 2 3

so how can I make it to work give me 1 4 9 (eg times by itself) I thought this would work

Object.keys(obj).forEach(function(x){
    console.log(obj[x*x])
})

you need to multiply the values.

you have x*x which would be 'a'*'a' results in NaN .

obj[NaN] = undefined

 var obj = {a: 1, b: 2, c:3} Object.keys(obj).forEach(function(x){ console.log(obj[x] * obj[x]) }) 

You're almost there. this one does the job:

Object.keys(obj).forEach(function(x){
    console.log(obj[x]*obj[x])
 })

you can use Object.values in ES2016

Object.values(obj).forEach(function(x){
   console.log(x*x);
})

 var obj = {a: 1, b: 2, c:3} Object.keys(obj).forEach(function(x){ console.log(Math.pow(obj[x], 2)); }) 

Math.pow (x,y) => x x x*...y times...*x

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