javascript - 如何将数组中的值推送到 chrome 存储中?
问题描述
数组推送功能是创建嵌套数组而不是将值放在索引上。它在项目中创建嵌套项目,而不是将其添加到数组的索引中。我尝试了很多方法,但没有发现问题。我想在每个索引中添加数组,以便我可以检索它并创建它的 csv。我想要这样的输出: item[0]=[title,description,price,image] item 1 =[title,description,price,image] 依此类推,这里输入的值是我的 js:
$(function(){
var title='';
var price='';
var description='';
var image='';
var i=0;
var product =[];
var products=[];
$("#scrape").click(function(){
chrome.storage.sync.get(["key"],function(result){
if(result.key!=undefined){
i=result.key;
}
});
chrome.tabs.query({active:true,currentWindow:true},function(tabs){
chrome.tabs.sendMessage(tabs[0].id,{todo:"fetch"},function(response){
description =response.description;
title=response.title;
image=response.image;
price=response.price;
product=[title,price,image,description];
chrome.storage.sync.get(function(item){
if(item["products"] != undefined){
item["products"].push(product);
}
else{
item["products"]=product;
}
//console.log(item);
chrome.storage.sync.set({item});
i=i+1;
});
});
});
});
});
解决方案
将存储视为具有键和值的标准 JS 对象。products
在您的情况下,使用标准 JS 数组之类的键是有意义的。使用 chrome.storage 的唯一概念区别是您需要分别读取和写入值。
$('#scrape').click(function () {
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
chrome.tabs.sendMessage(tabs[0].id, {todo: 'fetch'}, response => {
chrome.storage.sync.get('products', ({products = []}) => {
products.push([
response.title,
response.price,
response.image,
response.description,
]);
chrome.storage.sync.set({products});
});
});
});
});
推荐阅读
- itfoxtec-identity-saml2 - ITfoxtec SAML 2.0 与 NET 5.0- 设置 cookie 名称
- asp.net - 如何使用 rdlc 报告查看器创建完整的响应式 asp.net 页面
- .net - 等待与 .GetAwaiter.GetResult() - .Net GraphServiceClient
- r - 正则表达式提取“specificWord”行上的数字
- php - Laravel 8 错误供应商/symfony/polyfill-mbstring/Mbstring.php
- typescript - 在打字稿中获取错误的字符串表示的规范方法是什么
- c++ - 使用 real() 和 imag() 为复杂变量赋值的问题
- javascript - 滚动时导航栏不改变背景颜色
- python - 如何在python的xml文件中访问子Childs?
- javascript - 我正在尝试制作一个显示位置的移动网络应用程序,但它不起作用?