我想替换我的数组中的所有值,这是代码:
var jsonImg = [
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg"}
];
var imgUrl = JSON.stringify(jsonImg);
var oldString = imgUrl;
var newString = oldString.replace(/https:\/\/example.amazonaws.com\/images-lib\//g,"cordova.url/");
$scope.Images = JSON.parse(newString);
但我认为JSON.Stringfly和JSON.Parse在这里有点多余,你认为这是替换所有值JSON.Stringfly和JSON.Parse的最有效方法吗?有没有其他替代方法呢?请检查这里的小提琴: https://jsfiddle.net/dedenbangkit/zu7utr6a/3/
答案 0 :(得分:1)
你是对的。无需转换为字符串和返回。虽然当涉及阵列中的少量值时,就效率而言并不重要。但是,当你可以为数组本身提供如此强大的函数时,为什么要转换为字符串和返回。
类似的东西:
$scope.Images = jsonImg.map(function(obj) {
obj.url = "cordova.url" + obj.url.substr(obj.url.lastIndexOf("/"))
return obj;
});
答案 1 :(得分:1)
根据我的理解,在所有图片网址中重复cdn路径是多余的。您应该创建另一个保存此路径的变量,当您需要使用它时,只需连接两个字符串。这样,您可以轻松更改cdn路径,而无需进行处理。
<强>示例强>
出于演示目的,我使用了Math.random
,但你可以说明你的情况。
function ImgCtrl($scope) {
var s3 = "https://s3-ap-southeast-1.amazonaws.com/publixx-statics/images-lib/";
var cordava = "cordova.url/";
var urls = [{
"url": "1496846856-Retina 01.jpg"
}, {
"url": "1496846856-Retina 02.jpg"
}, {
"url": "1496846856-Retina 03.jpg"
}]
$scope.path = Math.floor(Math.random() * 100) % 2 === 0 ? s3 : cordava;
$scope.Images = urls;
console.log($scope.Images[0].url)
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app>
<div ng-controller="ImgCtrl">
<ul>
<li ng-repeat="Image in Images">
{{path}}{{Image.url}}
</li>
</ul>
</div>
</div>
&#13;
根据我们的讨论,您可以有两个选项:
// Sample 1
var flag = Math.floor(Math.random() * 100) % 2 === 0;
function getImagePath(image) {
var s3 = "https://s3-ap-southeast-1.amazonaws.com/publixx-statics/images-lib/";
var cordava = "cordova.url/";
return (flag ? s3 : cordava) + image;
}
// Usage:
var url = getImagePath(imageUrl)
// Sample 2
var path = (function() {
var s3 = "https://s3-ap-southeast-1.amazonaws.com/publixx-statics/images-lib/";
var cordava = "cordova.url/";
return flag ? s3 : cordava;
})()
var url = path + imageUrl;
答案 2 :(得分:1)
var jsonImg = [
{ 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg' },
{ 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg' },
{ 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg' },
];
jsonImg.map(function(image) {
var split = image.url.split('/');
var fileName = split[split.length - 1];
image.url = 'cordova.url/' + fileName;
});
这会改变jsonImg
数组中的所有字符串,将https://example.amazonaws.com/images-lib/
网址替换为cordova.url/
。