The Object.keys() method returns an array of the names of the enumerable properties and methods of an object.
Object.keys(object)
An array that contains the names of the enumerable properties and methods of the object.
ES6新语法(oh, 老语法...),简单,就是需要了解并记忆,这以后会常用~ 晚安!~
const ArraytoObj = (keys = [], values = []) =>{if(keys.length === 0 || values.length === 0) return {}
const len = keys.length >values.length ? values.length : keys.length
// if you want save all the keys, and the value could be undefined, you can use keys.forEach function instead of for loop
const obj = {}
for(let i = 0i <len++i) {
obj[keys[i]] = values[i]
}
return obj
}
// test cases
expect(ArraytoObj(['ka', 'kb'], ['va', 'vb'])).to.eql({ ka: 'va', kb: 'vb' })
expect(ArraytoObj(['ka', 'kb', 'kc'], ['va', 'vb'])).to.eql({ ka: 'va', kb: 'vb' })
expect(ArraytoObj(['ka', 'kb'], ['va', 'vb', 'vc'])).to.eql({ ka: 'va', kb: 'vb' })
expect(ArraytoObj([], ['va', 'vb'])).to.eql({})
expect(ArraytoObj(['ka', 'kb'], [])).to.eql({})
expect(ArraytoObj()).to.eql({})