为什么要比较相同的数组值和对象返回false?

时间:2018-11-08 16:04:05

标签: javascript arrays object

数组: 我有2个带有值的变量;

EmpMaster(Division_Description, start_date, leaving_date)

对象:

var a = [1,2];
var b = [1,2];
a === b; //return false

字符串:

var a = {
   value: 'foo'
}
var b = {
   value: 'foo'
}
a === b //return false

为什么他们要退还?

1 个答案:

答案 0 :(得分:0)

var a = [1,2];
var b = [1,2];


// Here you compare the instances of the Array which are objects.
// The values are not compared

console.log(a === b);

// To compare the values do :
console.log(a.length === b.length && a.every(x => b.includes(x)));

console.log('-----------');

var a = {
   value: 'foo'
}

var b = {
   value: 'foo'
}

// Here it's the same thing, you compare the object 
// (the container) and not the content
console.log(a === b);

// To compare the values do :
console.log(a.value === b.value);

console.log('-----------');

var a = '1000';
var b = '200';

// Here you compare two strings. What is happening is that all 
// character have a special value
// Look at google about ASCII
// 
// It compares character by character starting by the left
// 1 is inferior to 2 so 1000 is not superior to 200
console.log(a > b);

// To compare the values do :
console.log(Number(a) > Number(b));