我正在尝试创建一个名为maybeNoises
的函数来测试数组是否有噪音,然后将它们打印到控制台。
提示如下:
Function should take an object, if this object has a noises array return them as a string separated by a space, if there are no noises return 'there are no noises' (2, 1, 3)
这是我的代码:
function maybeNoises(object) {
if (object.noises) {
return object.noises.join(" ");
} else if (object["noises"].isArray(undefined)) {
console.log("THIS TEST IS STUPID AND PISSING ME OFF");
} else(object["noises"].isArray(null));
return 'there are no noises';
}
这就是它正在测试的内容:
QUnit.test(“maybeNoises():应该取一个对象,如果这个对象有一个noises数组,则将它们作为由空格分隔的字符串返回,如果没有噪声返回'没有噪音'”,
function(assert) {
assert.equal(maybeNoises({
noises: ["bark", "woof", "squeak", "growl"]
}), "bark woof squeak growl");
assert.equal(maybeNoises({
noises: []
}), "there are no noises");
assert.equal(maybeNoises({}), "there are no noises");
});
我做错了什么?
答案 0 :(得分:0)
我编辑了我的答案,总结了所有问题:
1。)检查是否有噪音阵列。
你想做Array.isArray(object.noises)
或者如果你不太可能在你的javascript实现中工作,你可以在这里检查其他替代方案:Check if object is array?
2.)检查数组是否包含元素:
object.noises.length
可用于查看数组是否有任何条目。
3。)将噪音作为数组返回 你已经正确地想出来了。
答案 1 :(得分:0)
您的代码存在问题
else(object["noises"].isArray(null))
不是有效的语法if (object.noises) return object.noises.join(" ");
- 您的第一个测试假定object
具有名为noises
的属性,并且此noises
对象具有名为join
的属性,该属性是function
......没有经过测试就可以承担这个问题! ...如果噪音为true
,例如,true
没有加入属性,该怎么办!如果对象为null / undefined会怎么样?它甚至没有一种叫做噪音的财产!object["noises"].isArray(undefined)
数组没有isArray
函数,只有Array
(字面意思是数组,而不是"数组")具有该函数,并且它的参数应该是你想要测试的对象所以,这就是你需要做的所有事情
function maybeNoises(object) {
// we know nothing about object yet, so lets not assume
if (object && object.noises) { // check that object and object.noises are "something"
// here, we know that object.noises is "something"
if (Array.isArray(object.noises)) { // check that object.noises is an Array
// here we know that object.noises is an array, so, it has a length
if (object.noises.length > 0) { // check length is > 0
return object.noises.join(' ');
}
}
}
return 'there are no noises'; // didn't pass the above tests, so return this string
}