访问 Javascript 中的未定义值
Accessing Undefined Value in Javascript
我在处理这个问题时遇到了一些问题。
用户可以将图像上传到我的表单中名为 photo_id 的变量。我取photo_id中的第一个文件对象并将其发送到数据库以创建一个文件对象。
if (photo_id) {
var file=photo_id[0]
//send to database and set id to new object created
}
但是,有时用户会单击文件上传按钮但不会添加文件。仍然创建一个 fileList 对象并将其放入 photo_id 变量,但它的长度为 0,这使得它未定义。
在这种情况下,当我 运行 这个:
if (photo_id ) {
var file=photo_id[0]
....
}
我明白了
Cannot read property '0' of undefined
我需要检查以确保 FileList 长度大于 0,但即使我这样做了:
if (photo_id[0].length >0) {
var file=photo_id[0]
//send to database and set id to new object created
}
我收到错误:
cannot read length of undefined
如何检查 FileList 存在且长度 >0 的两种情况?
您正在检查第一个元素的长度,但没有第一个元素。使用:
if (photo_id && photo_id.length > 0) {...}
我在处理这个问题时遇到了一些问题。
用户可以将图像上传到我的表单中名为 photo_id 的变量。我取photo_id中的第一个文件对象并将其发送到数据库以创建一个文件对象。
if (photo_id) {
var file=photo_id[0]
//send to database and set id to new object created
}
但是,有时用户会单击文件上传按钮但不会添加文件。仍然创建一个 fileList 对象并将其放入 photo_id 变量,但它的长度为 0,这使得它未定义。
在这种情况下,当我 运行 这个:
if (photo_id ) {
var file=photo_id[0]
....
}
我明白了
Cannot read property '0' of undefined
我需要检查以确保 FileList 长度大于 0,但即使我这样做了:
if (photo_id[0].length >0) {
var file=photo_id[0]
//send to database and set id to new object created
}
我收到错误:
cannot read length of undefined
如何检查 FileList 存在且长度 >0 的两种情况?
您正在检查第一个元素的长度,但没有第一个元素。使用:
if (photo_id && photo_id.length > 0) {...}