js 转换(字符串、数组、对象)

108 阅读1分钟

JS字符串和数组之间的转换

// 字符串转换为数组

var string = '123,456,789';
var stringResult = string.split(',');
console.log(stringResult) //输出["123", "456", "789"]

// 数组转换为字符串

var array = ['abc', 'def', 'hig']
var arrayResult = array.join(',')
console.log(arrayResult) // 输出"abc,def,hig"

对象或值转换成JSON字符串

JSON.stringify() 方法能将一个 JavaScript 对象或值转换成一个 JSON 字符串。

//初始化一个 user 对象
const user = {
 "name" : "Prateek Singh",
 "age" : 26
}

console.log(user); // [object Object]

console.log(JSON.stringify(user)); // "{ "name" : "Prateek Singh", "age" : 26 }"

额外经典面试题

1 + '1'                      // '11'
true + 0                    //  1
{}+[]                       //  0
4 + {}                      // "4[object Object]"
4 + [1]                     // "41"
'a' + + 'b'                  // "aNaN"
console.log ( [] == 0 )      // true
console.log ( ! [] == 0 )   // true
console.log ( [] == ! [] )  // true
console.log ( [] == [] )    // false
console.log({} == !{})      // false
console.log({} == {})      // false