基于传入的值构建数组
Building an Array Based on Passed-in Values
我正在开发一个函数,我在其中检查传入的值,然后将其添加到数组中。我有什么不工作,我只是得到一个空数组:
let category = 'client';
function builtArray() {
let catArray = [];
if (category === 'client') {
catArray.push('client');
}
console.log(catArray);
}
我错过了什么?
如果我正确理解你的问题,
let category = 'client';
function builtArray() {
let catArray = [];
if (category === 'client') {
catArray.push('client');
}
console.log(catArray);
}
应该是
let category = 'client';
function builtArray(cat) {
let catArray = [];
if (cat === 'client') {
catArray.push(cat);
}
console.log(catArray); // => ['client']
}
builtArray(category);
你必须"invoke"它的功能运行。这意味着用 ()
调用它,这就是我最后所做的。
你将 "category" 作为参数传递给函数,函数重命名你传入的内容(如 cat
),然后它检查是否变量等于字符串 client
,如果是,则将其插入 catArray
.
我想你希望在函数之后保留数组,在这种情况下在函数外声明它。
let category = 'client';
let catArray = [];
function builtArray(str) {
if (category === 'client') //this will only allow 'client' to be inserted
{
catArray.push(str);
}
console.log(catArray);
}
然后根据需要调用:
builtArray('client');
我正在开发一个函数,我在其中检查传入的值,然后将其添加到数组中。我有什么不工作,我只是得到一个空数组:
let category = 'client';
function builtArray() {
let catArray = [];
if (category === 'client') {
catArray.push('client');
}
console.log(catArray);
}
我错过了什么?
如果我正确理解你的问题,
let category = 'client';
function builtArray() {
let catArray = [];
if (category === 'client') {
catArray.push('client');
}
console.log(catArray);
}
应该是
let category = 'client';
function builtArray(cat) {
let catArray = [];
if (cat === 'client') {
catArray.push(cat);
}
console.log(catArray); // => ['client']
}
builtArray(category);
你必须"invoke"它的功能运行。这意味着用
()
调用它,这就是我最后所做的。你将 "category" 作为参数传递给函数,函数重命名你传入的内容(如
cat
),然后它检查是否变量等于字符串client
,如果是,则将其插入catArray
.
我想你希望在函数之后保留数组,在这种情况下在函数外声明它。
let category = 'client';
let catArray = [];
function builtArray(str) {
if (category === 'client') //this will only allow 'client' to be inserted
{
catArray.push(str);
}
console.log(catArray);
}
然后根据需要调用:
builtArray('client');