我实际上已经通过了这个测试,但我对一件事并不满意。
如果我通过以下内容:
var expected = [-5, '0', 5];
var actual = [-5, 0, 5];
我会得到这个结果:
FAILED [check mixed elements] Expected "-5,0,5", but got "-5,0,5"
正如您所看到的,它显示了两个完全相同的东西,其中必须是:
FAILED [check mixed elements] Expected "-5,'0',5", but got "-5,0,5"
如果我在assertArraysEqual函数的FAILED选项上使用了arrayToString函数,它将如下所示:
FAILED [check mixed elements] Expected "-,5,',0,',5", but got "-,5,0,5"
知道如何解决这个问题吗?
这是我的完整代码的副本:
function arrayToString(array) {
var convertedArrayToString = '';
if(array[0] === "-"){
array.splice(0, 2, (array[0] + array[1]));
}
for (var i = 0; i < array.length; i++) {
if(typeof array[i] === 'number'){
convertedArrayToString += Number(array[i]);
}else if(typeof array[i] === 'string'){
convertedArrayToString += `'${array[i]}'`;
} else {
convertedArrayToString += array[i];
}
}
return convertedArrayToString.split('').join(',');
}
function assertArraysEqual(actual, expected, testName) {
if (arrayToString(actual) === arrayToString(expected)) {
return console.log('passed');
} else {
return console.log(`FAILED [${testName}] Expected "${arrayToString(expected)}", but got "${arrayToString(actual)}"`);
}
}
var expected = [-5, '0', 5];
var actual = [-5, 0, 5];
assertArraysEqual(actual, expected, 'check mixed elements');
var expected = [1, 2, 3, 4];
var actual = [1, 2, 4];
assertArraysEqual(actual, expected, 'check length');
var expected = ['b', 'r', 'o', 'k', 'e', 'n'];
var actual = 'broken'.split('');
assertArraysEqual(actual, expected, 'splits string into array of characters');
答案 0 :(得分:2)
您应该使用JSON.stringify()
:
return console.log(`FAILED [${testName}] Expected ${JSON.stringify(expected)}, but got ${JSON.stringify(actual)}`);
应该给你:
FAILED [check mixed elements] Expected [-5,"0",5], but got [-5,0,5]
答案 1 :(得分:2)
您可以为每个元素使用JSON.stringify
来构建字符串。
function arrayToString(array) {
return JSON.stringify(array);
}
console.log(arrayToString([5, '0', 5]));