我要实现的目标是,每当将新客户端添加到客户端阵列时,我都希望函数返回“欢迎(新客户名称),您(他在阵列中的位置)在行中”。 / p>
我在做什么错?我正在尝试让新客户端的索引加1,以便它从1开始计数。
let clients = ['Smith', 'Stebve', 'John']
function clientQue(array, newCustomer) {
array.splice(1, 0, newCustomer)
return "Welcome " + newCustomer + ", you are number " + parseInt(array.indexOf('newCustomer')) + 1 + " in line.";
}
clientQue(clients, 'Bob');
答案 0 :(得分:2)
您缺少paranthethesis(),无法进行字符串连接并首先进行数学运算
"Welcome " + newCustomer + ", you are number " + (array.indexOf(newCustomer) + 1 ) + " in line.";
由于您始终使用array.splice
插入第一个索引位置,因此,您也可以删除所有array.indexOf
并始终只输出1
。
答案 1 :(得分:1)
您可以取消移动新客户端,并将获得的数组新长度作为值。
function clientQue(array, newCustomer) {
return "Welcome " + newCustomer + ", you are number " + array.unshift(newCustomer) + " in line.";
}
let clients = ['Smith', 'Stebve', 'John']
console.log(clientQue(clients, 'Bob'));
答案 2 :(得分:1)
这将为您工作(我总是喜欢在缩进字符串时使用``
让客户= ['Smith','Stebve','John']
function clientQue(array, newCustomer) {
array.splice(1, 0, newCustomer)
return `Welcome ${newCustomer} you are number ${parseInt(array.indexOf(newCustomer)) + 1} in line.`;
}
let message = clientQue(clients, 'Bob');
console.log(message)
这是输出
欢迎鲍勃,您排在第二位。
答案 3 :(得分:0)
从newCustomer中删除此部分中的引号。需要评估为“鲍勃”。
parseInt(array.indexOf(newCustomer))
答案 4 :(得分:0)
let clients = ['Smith', 'Stebve', 'John']
function clientQue(array, newCustomer) {
return "Welcome " + newCustomer + ", you are number " + (parseInt([...array, newCustomer].indexOf(newCustomer)) + 1) + " in line.";
}
clientQue(clients, 'Bob');
这应该返回您需要的内容,但是Array.splice会改变原始数组,这意味着它还会修改原始数组的值。更改给定参数的值可能有害。
[...array]
根据旧数组的元素和
创建一个新数组[...array, newCustomer]
将新元素放入新数组中。
答案 5 :(得分:0)
因为我的答案已被删除并且我没有机会对其进行更新,所以我会重新发布
几件事:
调用.splice
会从数组中删除一个元素,根据您的问题,这似乎并不是所希望的结果。
此外,您无需调用array.indexOf()
,因为数组的长度将成为新添加的客户端的位置。
您可以使用一个函数,该函数的名称为“ Jeff”,然后将其添加到客户端数组中,然后返回欢迎消息。这是一个例子。
var clients = ["bob", "jane", "isaac", "harry"];
function addClient(name) {
clients.push(name);
return "Welcome " + name + " you are position " + clients.length + " in array";
}
console.log(addClient("Jeff"));
答案 6 :(得分:0)
由于客户是一个队列,我想您希望将新客户放在数组的前面,因此您应该在splice
中使用索引0。即
array.splice(0, 0, newCustomer);
如果您想将newCustomer放在后面,则可以改用push()
。 (我更喜欢实际使用push()
。)
array.indexOf()
应该返回一个数字,因此您无需使用parseInt()
。
但是,由于在递增索引之前正在使用字符串操作,因此对于加法操作应使用括号。即
'Welcome ' +
newCustomer +
', you are number ' +
(array.indexOf(newCustomer) + 1) +
' in line.'
注意:由于Bob是队列末尾的新客户,因此您可能需要将索引计算更改为:(array.length - array.indexOf(newCustomer))
。
让我们把它们放在一起,
let clients = ['Smith', 'Stebve', 'John'];
function clientQue(array, newCustomer) {
array.splice(0, 0, newCustomer);
return (
'Welcome ' +
newCustomer +
', you are number ' +
(array.indexOf(newCustomer) + 1) +
' in line.'
);
}
const q = clientQue(clients, 'Bob');
console.log(q); // Welcome Bob, you are number 1 in line.
console.log(clients); // [ 'Bob', 'Smith', 'Stebve', 'John' ]