Javascript 与“===”相等的字符串
Javascript String Equality with "==="
我正在编写一个 React 应用程序,在尝试消除所有警告时我发现了一个奇怪的错误...
handleLike = id => {
const movies = [...this.state.movies];
const movie = movies.filter(obj => obj._id === id);
if (movie.map(obj => obj.liked) == "fa fa-heart-o") {
movie.map(obj => (obj.liked = "fa fa-heart"));
this.setState({ movies });
} else {
movie.map(obj => (obj.liked = "fa fa-heart-o"));
this.setState({ movies });
}
在 if (movie.map(obj => obj.liked) == "fa fa-heart-o") 我不使用 [=18= 输入检查](===) 因为由于某种原因它会是假的,但是 obj.liked 在控制台使用 typeof 记录它之后,它说它是一个字符串,所以它绝对应该是真实的,即使在我之后添加了 ToString() 它没有得到真实...我仔细检查了所有内容,我是否遗漏了什么?
提前致谢!
你做了很多不必要的 map
ping。
1) movies.filter(obj => obj._id === id);
将 return 一个元素的数组,它是一个 movie
对象。要获取实际的电影对象,您需要改用 movies.filter(obj => obj._id === id)[0];
。您可能还想考虑使用 find
(to grab the movie object) or findIndex
来确定您想要的电影的索引。
2) if (movie.map(obj => obj.liked) == "fa fa-heart-o")
没有意义 - 您正在尝试比较一个数组(map
将 总是 return 一个新数组) 到一个字符串。我很惊讶这完全有效。
根据您的评论,我可能会按如下方式重写您的代码:
handleLike = id => {
const movies = [...this.state.movies];
// Find the index of the movie where `_id` matches `id`
const movie = movies.find(obj => obj._id === id);
// If the movie at the index is liked (either true/false),
// give the object a new property "icon" and give it a heart
if (movie.liked) {
movie.icon = "fa fa-heart";
} else {
// Otherwise give it an empty heart
movie.icon = "fa fa-heart-o";
}
// Set the new state (only once)
this.setState({ movies });
}
我正在编写一个 React 应用程序,在尝试消除所有警告时我发现了一个奇怪的错误...
handleLike = id => {
const movies = [...this.state.movies];
const movie = movies.filter(obj => obj._id === id);
if (movie.map(obj => obj.liked) == "fa fa-heart-o") {
movie.map(obj => (obj.liked = "fa fa-heart"));
this.setState({ movies });
} else {
movie.map(obj => (obj.liked = "fa fa-heart-o"));
this.setState({ movies });
}
在 if (movie.map(obj => obj.liked) == "fa fa-heart-o") 我不使用 [=18= 输入检查](===) 因为由于某种原因它会是假的,但是 obj.liked 在控制台使用 typeof 记录它之后,它说它是一个字符串,所以它绝对应该是真实的,即使在我之后添加了 ToString() 它没有得到真实...我仔细检查了所有内容,我是否遗漏了什么?
提前致谢!
你做了很多不必要的 map
ping。
1) movies.filter(obj => obj._id === id);
将 return 一个元素的数组,它是一个 movie
对象。要获取实际的电影对象,您需要改用 movies.filter(obj => obj._id === id)[0];
。您可能还想考虑使用 find
(to grab the movie object) or findIndex
来确定您想要的电影的索引。
2) if (movie.map(obj => obj.liked) == "fa fa-heart-o")
没有意义 - 您正在尝试比较一个数组(map
将 总是 return 一个新数组) 到一个字符串。我很惊讶这完全有效。
根据您的评论,我可能会按如下方式重写您的代码:
handleLike = id => {
const movies = [...this.state.movies];
// Find the index of the movie where `_id` matches `id`
const movie = movies.find(obj => obj._id === id);
// If the movie at the index is liked (either true/false),
// give the object a new property "icon" and give it a heart
if (movie.liked) {
movie.icon = "fa fa-heart";
} else {
// Otherwise give it an empty heart
movie.icon = "fa fa-heart-o";
}
// Set the new state (only once)
this.setState({ movies });
}