有没有办法使用JavaScript在新变量中切片字符串?

时间:2020-06-30 13:39:04

标签: javascript if-statement slice

我正在使用JavaScript弹出窗口,当用户访问网页时,会有一个图表显示您的名字?因此,用户需要输入他的名字。在一个领域。如果用户输入两个单词,则程序会将名称分为单独的名字和姓氏字符串。

我正在使用此代码,但不能使用slice方法的姓氏,它只是将名字全都给了。我在做什么错了?

var fullname;
fullname = prompt("What is your name?");
fullname.indexOf(" ");

var indexOfSpace = fullname.indexOf(" ");
var firstname = "";
var lastname = "";

if (fullname.indexOf = -1) {
  firstname = fullname;
  lastname = "";
} else {
  firstname = fullname;
  lastname = fullname.slice(fullname.indexOf + 1);
}


console.log("Your visitor wrote : " + fullname + "\n\n" +
  "So his first name is: " + firstname + "\n" +
  " and" + "\n" +
  "his lastname is: " + lastname
);
alert("You wrote : " + fullname + "\n\n" +
  "So your first name is: " + firstname + "\n" +
  " and" + "\n" +
  "your lastname is: " + lastname + "!"
);

1 个答案:

答案 0 :(得分:0)

  • if (fullname.indexOf = -1) indexOf需要一个参数-您可能是说if (indexOfSpace === -1)

  • =是分配。 =====是比较

  • firstname = fullname.slice(0,indexOfSpace);

  • lastname = fullname.slice(indexOfSpace+1)

固定代码。

let fullname = prompt("What is your name?");
let firstname = "";
let lastname = "";

const indexOfSpace = fullname.indexOf(" "); // contains -1 if not found, 0 or higher if found

if (indexOfSpace === -1) {
  firstname = fullname;
  lastname = "";
} else {
  firstname = fullname.slice(0,indexOfSpace);
  lastname = fullname.slice(indexOfSpace + 1);
}


console.log("Your visitor wrote : " + fullname + "\n\n" +
  "So his first name is: " + firstname + "\n" +
  " and" + "\n" +
  "his lastname is: " + lastname
);
alert("You wrote : " + fullname + "\n\n" +
  "So your first name is: " + firstname + "\n" +
  " and" + "\n" +
  "your lastname is: " + lastname + "!"
);

使用拆分的代码

let fullname = prompt("What is your name?");
let [firstname, lastname] = fullname.split(" "); // split using destructuring
lastname = lastname || ""; // space if undefined (falsy actually) using the OR operand

console.log("Your visitor wrote : " + fullname + "\n\n" +
  "So his first name is: " + firstname + "\n" +
  " and" + "\n" +
  "his lastname is: " + lastname
);
alert("You wrote : " + fullname + "\n\n" +
  "So your first name is: " + firstname + "\n" +
  " and" + "\n" +
  "your lastname is: " + lastname + "!"
);