虽然值在数组中,但我不明白为什么indexOf()会打印-1。 函数include()的结果相同,返回false。
我认为我听不懂或忘记了一些东西。
您是否知道当我们看到值在数组中时为什么结果为负?
谢谢
var i = 0
let array = []
class MovieRow extends React.Component {
constructor(props) {
super(props)
this.addFavorite = this.addFavorite.bind(this)
this.deleteFavorite = this.deleteFavorite.bind(this)
this.state = {
isFaved: false,
favMovie: ""
}
}
addFavorite() {
this.setState({isFaved: true})
this.state.favMovie = "".concat(baseURL, 'movie/', this.props.movie.id ,'?api_key=', APIKEY)
var counts = []
for (var i = 0; i < myFavoriteMovies.length; i++) {
var index = myFavoriteMovies[i]
counts[index] = counts[index] ? counts[index] + 1 : 1;
}
if(myFavoriteMovies.indexOf(this.state.favMovie) === -1) {
myFavoriteMovies.push(this.state.favMovie)
localStorage.setItem(this.props.movie.id, this.state.favMovie)
}
}
deleteFavorite() {
this.setState({isFaved: false})
var removeThisMovie = myFavoriteMovies.indexOf(this.state.favMovie)
myFavoriteMovies.splice(removeThisMovie,1)
localStorage.removeItem(this.props.movie.id,removeThisMovie)
}
componentDidMount() {
console.log(array)
console.log("Value = "+this.props.movie.id)
console.log("Res indexOf = " +array.indexOf(this.props.movie.id))
}
答案 0 :(得分:6)
indexOf
和includes
搜索完全匹配。
this.props.movie.id
将为491418
,而数组中的值为"491418"
。
您需要将this.props.movie.id
转换为字符串。
array.indexOf("" + this.props.movie.id)