[英]JS - beginner - function isMaleName()
In polish language most of the female name end in letter "a", which help to quickly identify the gender.在波兰语中,大多数女性名字以字母“a”结尾,这有助于快速识别性别。 Except is "Bonawentura" which is male name.
除了男性名字“Bonawentura”。
I need to write function which will tell:我需要写 function 它将告诉:
This is what I did: example 1:这就是我所做的:示例 1:
function isMaleName(name) {
let pieces = name.split("");
let last = pieces[pieces.length - 1];
if ((name = "bonawentura")) {
return true;
} else if ((last = "a")) {
return false;
} else {
return true;
}
}
2 conditions complete: 2个条件完成:
example 2:示例 2:
function isMaleName(name) {
let pieces = name.split("");
let last = pieces[pieces.length - 1];
if ((last = "a")) {
return false;
} else {
return true;
}
}
1 condition complete: 1条件完成:
You are assigning a Value instead of checking it.您正在分配一个值而不是检查它。
You should use name == "bonawentura"
instead of name = "bonawentura"
您应该使用
name == "bonawentura"
而不是name = "bonawentura"
function isMaleName(name) {
let pieces = name.split("");
let last = pieces[pieces.length - 1];
if (name === "bonawentura") {
return true;
} else if (last === "a") {
return false;
} else {
return true;
}
}
I think it should be look like this, use two or three =
instead of using one =
.我认为它应该是这样的,使用两个或三个
=
而不是使用一个=
。
You can use =
operator it's use to store value in variable, but if you use ==
it's for equality operator and if you can use ===
it is identity operator您可以使用
=
运算符,它用于将值存储在变量中,但是如果您使用==
它用于相等运算符,如果您可以使用===
它是身份运算符
Your problem is:你的问题是:
if ((name = "bonawentura"))
if ((last = "a"))
Use this code in if condition在 if 条件下使用此代码
if ((name == "bonawentura"))
if ((last == "a"))
Or或者
if ((name === "bonawentura"))
if ((last === "a"))
You could do it in one line, and support lowercase/uppercase/boNAweNtura :您可以在一行中完成,并支持小写/大写/boNAweNtura:
const isMaleName = name => !name.endsWith("a") || name.toLowerCase()==="bonawentura"; console.log(isMaleName("Joe")) // true console.log(isMaleName("Lena")) // false console.log(isMaleName("boNAweNtura")) // true console.log(isMaleName("David")) // true console.log(isMaleName("Sara")) // false
My comment above was maybe a bit misleading.我上面的评论可能有点误导。 So here in full:
所以这里是完整的:
function isMaleName(name) {
// convert input to lowercase
name = name.toLowerCase();
// check if it's the fixed string 'bonawentura'
return name === 'bonawentura'
// if not, check if it not ends with an 'a'.
|| 'a' !== name[name.length - 1];
}
Refs:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.