如何访问 JavaScript 中没有 Key 的对象的值
How to access the value of an object that doesn't have a Key in JavaScript
我正在尝试加载本地图像并在 JavaScript 中将其转换为 Base64(不加载到浏览器)。当我运行以下代码时:
// https://www.npmjs.com/package/image-to-base64
// installation: npm i -S image-to-base64
const image_path = "1.jpg" // Path to the image
const imageToBase64 = require('image-to-base64');
const image_base64 = imageToBase64(image_path)
console.log(typeof image_base64) // object
Th Base64 字符串保存在“image_base64”变量中。 “image_base64”的数据类型是Object,但它没有任何Key。当我在控制台中打印“image_base64”时:
{'/9j/4AAQSkZJRgABAQAAAQABAAD/4RDcRXhpZgA'}
(比上面的要长很多。)
我想访问对象“image_base64”中的 Base64 字符串。我尝试了以下命令:
console.log(Object.values(image_base64))
console.log(image_base64[0])
但是,他们return:
[]
undefined
如果您知道如何访问对象中的字符串,请告诉我。
您得到的输出不是有效的 vase64 编码。您可以通过将数据输入 online base64 decoder.
来检查这一点
imageToBase64() 方法是异步的,returns 一个您不等待的承诺。
看看这样做会得到什么样的输出:
imageToBase64(image_path)
.then(function(image_base64) {
console.log(image_base64);
})
.catch(function(error) {
console.error(error);
});
如果你在 ES6 环境中,你可以await
承诺:
// async function required for Node < v14
async function convertImage(image_path) {
try {
const image_base64 = await imageToBase64(image_path);
// Do something with image_base64 data
console.log(image_base64);
} catch (error) {
console.error(error);
}
}
我检查了这个库,你从 imageToBase64 函数收到的值是一个承诺。要从 promise 中检索值,您可以这样做 -
let img64 = img64Lib(imgPath);
img64.then(result => {
console.log(result);
}).catch(err => console.log(err));
我正在尝试加载本地图像并在 JavaScript 中将其转换为 Base64(不加载到浏览器)。当我运行以下代码时:
// https://www.npmjs.com/package/image-to-base64
// installation: npm i -S image-to-base64
const image_path = "1.jpg" // Path to the image
const imageToBase64 = require('image-to-base64');
const image_base64 = imageToBase64(image_path)
console.log(typeof image_base64) // object
Th Base64 字符串保存在“image_base64”变量中。 “image_base64”的数据类型是Object,但它没有任何Key。当我在控制台中打印“image_base64”时:
{'/9j/4AAQSkZJRgABAQAAAQABAAD/4RDcRXhpZgA'}
(比上面的要长很多。)
我想访问对象“image_base64”中的 Base64 字符串。我尝试了以下命令:
console.log(Object.values(image_base64))
console.log(image_base64[0])
但是,他们return:
[]
undefined
如果您知道如何访问对象中的字符串,请告诉我。
您得到的输出不是有效的 vase64 编码。您可以通过将数据输入 online base64 decoder.
来检查这一点imageToBase64() 方法是异步的,returns 一个您不等待的承诺。
看看这样做会得到什么样的输出:
imageToBase64(image_path)
.then(function(image_base64) {
console.log(image_base64);
})
.catch(function(error) {
console.error(error);
});
如果你在 ES6 环境中,你可以await
承诺:
// async function required for Node < v14
async function convertImage(image_path) {
try {
const image_base64 = await imageToBase64(image_path);
// Do something with image_base64 data
console.log(image_base64);
} catch (error) {
console.error(error);
}
}
我检查了这个库,你从 imageToBase64 函数收到的值是一个承诺。要从 promise 中检索值,您可以这样做 -
let img64 = img64Lib(imgPath);
img64.then(result => {
console.log(result);
}).catch(err => console.log(err));