javascript JS基础考试29
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JS基础考试29相关的知识,希望对你有一定的参考价值。
function equalObject(a, b) {
let resultNum = 0;
const typeA = Object.prototype.toString.call(a);
const typeB = Object.prototype.toString.call(b);
if (typeA !== '[object Object]' && (typeA !== typeB)) {
throw Error('function type error');
}
let keyA = Object.keys(a);
let keyB = Object.keys(b);
if (keyA.length !== keyB.length) return false;
for (let i = 0;i < keyA.length;i++) {
let targetKey = keyA[i];
if (b[targetKey] == a[targetKey]) {
resultNum++;
} else {
return false;
}
}
return resultNum === keyA.length;
}
let obj1 = {
a: 1,
b: 2
};
let obj2 = {
a: 1,
b: 2
};
// equalObject(obj1, obj2);
console.log("equalObject(obj1, obj2)", equalObject(obj1, obj2));
console.log("equalObject({a:[]}, {a:[]})", equalObject({a:[]}, {a:[]}));
function equalArray(a, b) {
const typeA = Object.prototype.toString.call(a);
const typeB = Object.prototype.toString.call(b)
if (typeA !== '[object Array]' && (typeA !== typeB)) {
throw Error('function type error');
}
if (a.length !== b.length) return false;
for (let i = -1, item = a[i];item=a[++i];){
if (item !== b[i]) {
return false;
}
}
return true;
}
let arr1 = [1, 2, 5, 7, 9];
let arr2 = [1, 2, 5, 7, 9];
console.log('equalArray(arr1, arr2)', equalArray(arr1, arr2));
console.log('equalArray([1, 2], [1, 2])', equalArray([1, 2], [1, 2]));
console.log('equalArray([2, 1], [1, 2])', equalArray([2, 1], [1, 2]));
console.log("equalArray([1, 2], ['1', '2'])", equalArray([1, 2], ['1', '2']));
function equal(a, b) {
const typeA = Object.prototype.toString.call(a);
const typeB = Object.prototype.toString.call(b);
if (typeA === typeB) {
if (typeA === '[object Object]') {
// Object
let resultNum = 0;
let keyA = Object.keys(a);
let keyB = Object.keys(b);
if (keyA.length !== keyB.length) return false;
for (let i = 0;i < keyA.length;i++) {
let targetKey = keyA[i];
if (equal(b[targetKey], a[targetKey])) {
resultNum++;
} else {
return false;
}
}
return resultNum === keyA.length;
} else if (typeA === '[object Array]') {
// Array
if (a.length !== b.length) return false;
for (let i = -1, item = a[i];item=a[++i];){
if (!equal(item, b[i])) {
return false;
}
}
return true;
} else {
// Not Support
return a === b;
}
} else {
return false;
}
}
let obj1 = { a: [1, '2'], b: 2};
let obj2 = { b: 2, a: [1, '2']};
let arr1 = [1, 2, { a: 1, b: 2 }, 9];
let arr2 = [1, 2, { b: 2, a: 1 }, 9];
console.log("equal(obj1, obj2)", equal(obj1, obj2));
console.log("equal(arr1, arr2)", equal(arr1, arr2));
console.log("equal(obj1, arr1)", equal(obj1, arr1));
以上是关于javascript JS基础考试29的主要内容,如果未能解决你的问题,请参考以下文章
珠峰JavaScript培训VIP精品课程(价值14800)
node基础1--初识Node.js与内置模块
JS基础_自增和自减
JS实现十分钟倒计时代码实例
day29—JavaScript中DOM的基础知识应用
JavaScript学习--Item29 DOM基础详解